import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../layout/Home.vue'
// import Index from '../views/Error.vue'
import Login from '../views/Login'
import Dash from '../views/Dashboard'
// import { component } from 'vue/types/umd'
import _ from 'lodash'

// 解决了路由重复触发的报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch((err) => err)
}

Vue.use(VueRouter)

const routes = [
  // 后台首页
  {
    path: '/',
    name: 'Home',
    component: Home,
    children: [
      // 后台首页
      {
        path: '/',
        name: '后台首页',
        component: Dash
      }
    ]
  },
  // 登录页
  {
    path: '/login',
    component: Login
  },
  {
    path: '*',
    redirect: '/404'
  },
  // 错误处理页
  {
    path: '/404',
    component: () =>
      import(/* webpackChunkName: "error" */ '../views/Error.vue')
  }
] // component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')

// 1.0 提取静态路由
const AsyncRoutes = {
  path: '/',
  component: Home,
  children: [
    // 后台首页
    {
      path: '/',
      name: '后台首页',
      component: Dash
    },
    // 商品管理
    {
      path: '/goods',
      name: '商品管理',
      component: () => import(/* webpackChunkName: "goods" */ '../views/Goods'),
      children: [
        // 商品列表
        {
          path: '/goods/list',
          name: '商品列表',
          component: () =>
            import(
              /* webpackChunkName: "goods" */ '../views/Goods/GoodsList.vue'
            )
        },
        // 商品添加
        {
          path: '/goods/add',
          name: '商品添加',
          component: () =>
            import(
              /* webpackChunkName: "goods" */ '../views/Goods/GoodsAdd.vue'
            )
        },
        // 商品编辑
        {
          path: '/goods/edit/:id',
          name: '商品编辑',
          hidden: true,
          component: () =>
            import(
              /* webpackChunkName: "goods" */ '../views/Goods/GoodsEdit.vue'
            )
        }
      ]
    },
    // 订单管理
    {
      path: '/order',
      name: '订单管理',
      component: () =>
        import(/* webpackChunkName: "orders" */ '../views/Orders')
    },
    // 可视化数据
    {
      path: '/charts',
      name: '可视化数据',
      meta: { role: [1] },
      component: () =>
        import(/* webpackChunkName: "charts" */ '../views/Charts'),
      children: [
        // 订单管理
        {
          path: '/charts/order',
          name: '订单数据',
          component: () =>
            import(
              /* webpackChunkName: "charts" */ '../views/Charts/Orders.vue'
            )
        },
        // 商品管理
        {
          path: '/charts/sell',
          name: '商品数据',
          component: () =>
            import(
              /* webpackChunkName: "charts" */ '../views/Charts/SellCount.vue'
            )
        }
      ]
    },
    // 用户管理
    {
      path: '/users',
      name: '用户管理',
      meta: { role: [1, 2] },
      component: () => import(/* webpackChunkName: "users" */ '../views/Users'),
      children: [
        // 用户列表
        {
          path: '/users/list',
          name: '用户列表',
          meta: { role: [1] },
          component: () =>
            import(
              /* webpackChunkName: "users" */ '../views/Users/UserList.vue'
            )
        },
        // 用户添加
        {
          path: '/users/add',
          name: '用户添加',
          meta: { role: [1] },
          component: () =>
            import(/* webpackChunkName: "users" */ '../views/Users/UserAdd.vue')
        },
        // 修改密码
        {
          path: '/users/restpwd',
          name: '修改密码',
          meta: { role: [1, 2] },
          component: () =>
            import(/* webpackChunkName: "users" */ '../views/Users/ResePwd.vue')
        },
        // 个人中心
        {
          path: '/users/my',
          name: '个人中心',
          hidden: true,
          meta: { role: [1, 2] },
          component: () =>
            import(/* webpackChunkName: "users" */ '../views/Personal')
        }
      ]
    }
  ]
}

// 2.0 设计一个函数, 根据用户权限计算新的路由
export function getNewRoutes() {
  // role 1 超级管理员   2 普通管理员
  const role = JSON.parse(window.localStorage.getItem('users') || '{}').group_id
  if (!role) return
  const lastRoutes = filterRoutes(role, AsyncRoutes.children)
  // console.log(lastRoutes)
  // 路由计算出来了，但是没有添加到主路由上
  // ***** 核心语法  router.addRoutes()  添加数组    router.addRoute()  添加对象
  AsyncRoutes.children = lastRoutes
  // router.addRoutes([AsyncRoutes])
  router.addRoute(AsyncRoutes)

  // 3.0 在已有的路由上，再次过滤需要展示在侧边栏的路由，进行保存
  const menuArr = _.cloneDeep(lastRoutes)
  const newMenu = filterMenus(menuArr)
  // console.log(menuArr)
  localStorage.setItem('menu', JSON.stringify(newMenu))
}

function filterMenus(arr) {
  return arr.filter((item) => {
    if (item.hidden) {
      return false
    } else {
      if (item.children) {
        item.children = filterMenus(item.children)
      }
      return true
    }
  })
}

// 真正过滤数组的函数
function filterRoutes(n, arr) {
  // filter 方法会把满足条件的项保留
  return arr.filter((item) => {
    if (item.meta && item.meta.role) {
      if (item.meta.role.includes(n)) {
        // 证明是需要鉴权的，如果有children，最好再过滤一次
        if (item.children) {
          // 通过自身调用自身(递归的方式)把子路由也过滤出来
          item.children = filterRoutes(n, item.children)
        }
        return true
      } else {
        return false
      }
    } else {
      // 如果没有当前的字段，那么就保留公共的路由
      return true
    }
  })
}

const router = new VueRouter({
  routes
})

getNewRoutes()
// // 使用路由的导航守卫完成登录的拦截功能
// router.beforeEach((to, from, next) => {
//   // 根据登录之后保存的这个凭证能够知道是否登录
//   const users = window.localStorage.getItem('users') || '{}'
//   const token = JSON.parse(users).access_token
//   // const token = window.localStorage.getItem('token')
//   if (token) {
//     next()
//   } else {
//     if (to.path === '/login') {
//       next()
//     } else {
//       next('/login')
//     }
//   }
// })

// // 使用路由的导航守卫完成登录的拦截功能
router.beforeEach((to, from, next) => {
  // 根据登录之后保存的这个凭证就能够知道是否登录
  const users = window.localStorage.getItem('users') || '{}'
  const token = JSON.parse(users).access_token
  if (token) {
    next()
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
